<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          placeholder="请输入公告标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人员" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入操作人员"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="noticeType">
        <el-select v-model="queryParams.noticeType" placeholder="公告类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="noticeId" width="100" />
      <el-table-column
        label="公告标题"
        align="center"
        prop="noticeTitle"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="公告类型"
        align="center"
        prop="noticeType"
        :formatter="typeFormat"
        width="100"
      />
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
        width="100"
      />
      <el-table-column label="创建者" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:notice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.noticeType==='1'"
            @click="handleExamine(scope.row)"
          >部门发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.noticeType==='1'"
            @click="handleClass(scope.row)"
          >班级发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:notice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" placeholder="请选择">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 发布时选部门对话框 -->
    <el-dialog :title="title" :visible.sync="examineOpen" width="780px" append-to-body >
      <el-form ref="examineForm" :model="examineForm" :rules="rules" label-width="120px">
        <el-form-item label="部门" prop="depIds" style="width:600px;height:500px;">
          <treeselect style="width:500px" v-model="deptArrays" :options="deptOptions" 
                :multiple="true" :disableBranchNodes="true"
                :show-count="true" placeholder="请选择部门" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitExamineForm">确 定</el-button>
        <el-button size="mini" @click="examineCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="班级选择框" :visible.sync="openClassSelect" width="1000px" append-to-body>
      <el-form :model="queryParamsClass" ref="queryFormClass" :inline="true" v-show="showSearch" label-width="120px">
        <el-form-item label="归属校区" prop="campusId">
          <treeselect style="width:200px" v-model="queryParamsClass.campusId" :options="campusOptions" 
                  :multiple="false" :disableBranchNodes="true"
                  :show-count="true" placeholder="请选择归属校区" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input
            v-model="queryParamsClass.className"
            placeholder="请输入班级名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="行课学期" prop="classTerm">
          <el-select v-model="queryParamsClass.classTerm" placeholder="请选择行课学期" clearable size="small">
            <el-option
                    v-for="dict in classTermOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="行课时间" prop="classBeginDate">
          <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
        </el-form-item>
        -->
        <el-form-item label="班主任" prop="masterUserId">
          <el-select
                v-model="queryParamsClass.masterUserId"
                placeholder="请输入班主任"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="user in masterUserOptions"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId"
                />
              </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQueryClass">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryClass">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" ref="tableClassSelect" :data="classInfoList" @selection-change="handleSelectionChangeClass">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="归属校区" align="center" prop="campusName" width="180" />
        <el-table-column label="班级名称" align="center" prop="className" width="180" />
        <el-table-column label="开课科数" align="center" prop="subjectNum" width="100" />
        <el-table-column label="开课总天数" align="center" prop="subjectDays" width="100" />
        <el-table-column label="行课学期" :formatter="classTermFormat" align="center" prop="classTerm" width="100" />
        <el-table-column label="行课开始时间" align="center" prop="classBeginDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.classBeginDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行课结束时间" align="center" prop="classEndDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.classEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班主任" align="center" prop="masterUserName" width="100" />
      </el-table> 
      <pagination
        v-show="totalClass>0"
        :total="totalClass"
        :page.sync="queryParamsClass.pageNum"
        :limit.sync="queryParamsClass.pageSize"
        @pagination="getListClass"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleClassSelect">确定</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetClassCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice, exportNotice, examineNotice, classNotice } from "@/api/system/notice";
import { listClassInfo  } from "@/api/edu/classInfo";
import Editor from '@/components/Editor';
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listAllUserByDeptId } from "@/api/system/user";
import { treeselectByType } from "@/api/system/dept";


export default {
  name: "Notice",
  components: {
    Editor, Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示发布弹出层
      examineOpen: false,
      // 类型数据字典
      statusOptions: [],
      // 状态数据字典
      typeOptions: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: [],
      deptArrays: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined
      },
      examineParams: {
        deptArray: null
      },
      // 表单参数
      form: {},
      // 发布表单参数
      examineForm: {
        noticeId: null,
        deptArrays: null
      },
      // 班级查询内容
      queryParamsClass: {
        pageNum: 1,
        pageSize: 6,
        campusId: null,
        classCode: null,
        className: null,
        subjectType: null,
        classType: null,
        subjectNum: null,
        subjectDays: null,
        grade: null,
        classTerm: null,
        classBeginDate: null,
        classEndDate: null,
        masterUserId: null,
        status: '0',
      },
      openClassSelect: false,
      totalClass: 0,
      loadingText: '加载班级',
      campusOptions: [],
      classTermOptions: [],
      masterUserOptions: [],
      scheduleList: [],
      statusOptions: [],
      classInfoList: [],
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" }
        ],
        noticeType: [
          { required: true, message: "公告类型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    'deptArrays': 'makeDeptArray'
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("sys_notice_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_notice_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询公告列表 */
    getList() {
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    makeDeptArray() {
      let arrays = ''
      this.deptArrays.forEach(array => {
        if(array !== "" && array !== null) {
          arrays += array + ','
        }
      })
      this.examineParams.deptArray = arrays.substring(0, arrays.length-1)
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
        //console.log(JSON.stringify(this.deptOptions))
      });
    },
    // 公告状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 公告状态字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.noticeType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    resetExamineForm() {
      this.examineForm = {
        noticeId: undefined,
        examineForm: undefined,
      };
      this.resetForm("examineForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改公告";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeId != undefined) {
            updateNotice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeIds = row.noticeId || this.ids
      this.$confirm('是否确认删除公告编号为"' + noticeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delNotice(noticeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 发布按钮操作 */
    handleExamine(row) {
      this.resetExamineForm();
      const noticeIds = row.noticeId || this.ids;
      this.examineForm.noticeId = noticeIds;
      this.examineOpen = true;
      this.title = "部门选择";
    },
    /** 发布取消操作 */
    examineCancel() {
      this.examineOpen = false;
      this.resetExamineForm();
    },
    /** 发布确定操作 */
    submitExamineForm() {
      const noticeId = this.examineForm.noticeId;
      const deptIds = this.examineParams.deptArray.toString()
      this.$confirm('是否确认发布公告编号为"' + noticeId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return examineNotice(deptIds, noticeId);
        }).then(() => {
          this.msgSuccess("发布成功");
          this.examineOpen = false;
          this.getList();
        })
    },
    /** 班级发布按钮操作 */
    handleClass(row) {
      this.resetExamineForm();
      // 选择班级弹出框
      this.openClassSelect = true;
      const noticeIds = row.noticeId || this.ids;
      this.examineForm.noticeId = noticeIds;
      this.title = "班级选择";
      let that = this
      setTimeout(function () {
        that.queryCampus();
        that.getDicts("edu_class_term").then(response => {
          that.classTermOptions = response.data;
        });
        that.handleQueryClass() // 执行列表查询
      }, 500);
    },
    queryCampus() {
      // 查询校区（deptType = 1）
      treeselectByType("1").then(response => {
        this.campusOptions = response.data;
      })
    },
    handleQueryClass() {
      this.queryParamsClass.pageNum = 1;
      this.getListClass();
    },
    getListClass() {
      this.loading = true;
      listClassInfo(this.addDateRange(this.queryParamsClass, this.dateRange)).then(response => {
        this.classInfoList = response.rows;
        this.totalClass = response.total;
        this.loading = false;
        this.initClassHandler() // 初始化查询条件
      });
    },
    initClassHandler() {
      //this.$nextTick(() => {
        let that = this
        that.classInfoList.forEach((item, index) => {
          if(that.queryParams.classIds) {
            let v_classIds = that.queryParams.classIds + ','
            v_classIds.split(',').forEach(ele => {
              if(ele.toString() === item.classId.toString()) {
                // 判断在返回列表中存在，就设置选中
                this.$nextTick( ()=> {
                  this.$refs.tableClassSelect.toggleRowSelection(this.classInfoList[index], true)
                })
              }
            })
          }
        })
      //})
    },
    /** 重置按钮操作 */
    resetQueryClass() {
      this.dateRange = [];
      this.resetForm("queryFormClass");
      this.handleQueryClass();
    },
    handleSelectionChangeClass(selection) {
      this.queryParams.classIds = selection.map(item => item.classId).toString()
      this.queryParams.classNames = selection.map(item => item.className).toString()
      //console.log(this.queryParams.classIds)
    },
    classTermFormat(row, column) {
      return this.selectDictLabel(this.classTermOptions, row.classTerm)
    },
    handleClassSelect() {
      const noticeId = this.examineForm.noticeId;
      const classIds = this.queryParams.classIds;
      console.log(this.examineForm.noticeId)
      this.$confirm('是否确认发布公告编号为"' + noticeId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return classNotice(classIds, noticeId);
        }).then(() => {
          this.msgSuccess("发布成功");
          this.openClassSelect = false;
          this.getList();
        })
      // this.queryParams.classIds = selection.map(item => item.classId).toString()
    },
    resetClassCancel() {
      this.openClassSelect = false
    },
  }
};
</script>